package com.course.server.service;

import cn.hutool.core.util.StrUtil;
import com.course.server.dto.${Entity}Dto;
import com.course.server.dto.PageDto;
import com.course.server.entity.${Entity};
import com.course.server.entity.${Entity}Example;
import com.course.server.mapper.${Entity}Mapper;
import com.course.server.util.UuidUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: Durian
 * @date: 2021/4/18 18:26
 */
@Service
public class ${Entity}Service {

    @Resource
    private ${Entity}Mapper ${entity}Mapper;

    public PageDto<${Entity}Dto> list(int page, int size) {
        PageHelper.startPage(page, size);
        ${Entity}Example example = new ${Entity}Example();
        List<${Entity}> ${entity}s = ${entity}Mapper.selectByExample(null);
        PageInfo<${Entity}> pageInfo = new PageInfo<>(${entity}s);

        List<${Entity}Dto> ${entity}Dtos = new ArrayList<>();
        for (${Entity} ${entity} : ${entity}s) {
            ${Entity}Dto ${entity}Dto = new ${Entity}Dto();
            BeanUtils.copyProperties(${entity}, ${entity}Dto);
            ${entity}Dtos.add(${entity}Dto);
        }
        PageDto<${Entity}Dto> pageDto = new PageDto<>();
        pageDto.setPage(page);
        pageDto.setSize(size);
        pageDto.setList(${entity}Dtos);
        pageDto.setTotal(pageInfo.getTotal());
        return pageDto;
    }

    public void save(${Entity}Dto ${entity}Dto) {
        ${Entity} ${entity} = new ${Entity}();
        BeanUtils.copyProperties(${entity}Dto, ${entity});
        if (StrUtil.isBlank(${entity}Dto.getId())) {
            insert(${entity});
        } else {
            update(${entity});
        }
    }

    public void delete(String id) {
        ${entity}Mapper.deleteByPrimaryKey(id);
    }

    private void insert(${Entity} ${entity}) {
        ${entity}.setId(UuidUtils.getShortUuid());
        ${entity}Mapper.insert(${entity});
    }

    private void update(${Entity} ${entity}) {
        ${entity}Mapper.updateByPrimaryKey(${entity});
    }
}